package model

import "github.com/pkg/errors"

type Plan struct {
	Model          `xorm:"extends"`
	PlanName       string `json:"plan_name" xorm:"varchar(20) notnull"`
	PipelineScript string `json:"pipeline_script" xorm:"text notnull"`
	ExecHosts      string `json:"exec_hosts" xorm:"text notnull"`
	CallKeys       string `json:"call_keys" xorm:"varchar(100) notnull"`
}

var _ DBOperations = &Plan{}

func (plan *Plan) Insert() (int64, error) {
	return DB.Insert(plan)
}

func (plan *Plan) Update() (int64, error) {
	if plan.ID == 0 {
		return 0, errors.New("id 为空！")
	}
	return DB.ID(plan.ID).Update(plan)
}

func (plan *Plan) Delete() (int64, error) {
	if plan.ID == 0 {
		return 0, errors.New("id 为空！")
	}
	return DB.ID(plan.ID).Delete(plan)
}

func GetPlanByID(id uint) (*Plan, error) {
	plan := new(Plan)
	has, err := DB.ID(id).Get(plan)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, nil
	}
	return plan, nil
}

func GetPlanByCallKeys(keys string) (*Plan, error) {
	plan := new(Plan)
	has, err := DB.Where("call_keys = ?", keys).Get(plan)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, nil
	}
	return plan, nil
}
